<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable />
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable />
      </el-form-item>
      <el-form-item label="工单来源">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource" placeholder="工单来源">
          <el-option label="客户订单" :value="1" />
          <el-option label="库存备货" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderType" placeholder="工单类型">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :key="dictData.id"
              :label="dictData.dictLabel"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 120px;" v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dictData in productionOrderStatusDictDataList"
              :label="dictData.dictLabel"
              :value="dictData.id"
              :key="dictData.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.materialCode" placeholder="物料编号" clearable />
      </el-form-item>
      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customerCode" placeholder="客户编号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 工具栏 -->
  <div class="toolbar">
    <el-button type="primary" @click="handleAdd">新增工单</el-button>
  </div>
  <!-- 列表 -->
  <el-card class="table-card">
    <el-table :data="productionOrderList" border stripe>
      <el-table-column prop="productionOrderCode" label="工单编号">
        <template #default="scope">
          <el-link type="primary" @click="handlerShowProcess(scope.row)">{{ scope.row.productionOrderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称" />
      <el-table-column prop="productionOrderSource" label="工单来源">
        <template #default="scope">
          {{ scope.row.productionOrderSource == 1 ? '客户订单' : '库存备货' }}
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderType" label="工单类型">
        <template #default="scope">
          {{scope.row.productionOrderType == 30 ?'自产':scope.row.productionOrderType == 31 ?'外协':'外购'}}
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号" />
      <el-table-column prop="materialCode" label="产品/物料编号" />
      <el-table-column prop="material.name" label="产品/物料名称" />
      <el-table-column prop="material.specification" label="规格" />
      <el-table-column prop="material.unit.name" label="单位" />
      <el-table-column prop="productionOrderQuantity" label="工单数量" />
      <el-table-column label="已生产数量">
        {{ 0 }}
      </el-table-column>
      <el-table-column prop="customer.code" label="客户编号" />
      <el-table-column prop="customer.name" label="客户名称" />
      <el-table-column prop="requestDate" label="需求日期" />
      <el-table-column prop="status" label="状态" >
        <template #default="scope">
          {{scope.row.status == 0 ? '草稿':scope.row.status == 1 ? '已确认': scope.row.status == 2? '已审核' : '已完成'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" v-if="scope.row.status == 0" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status == 0" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="small" v-if="scope.row.status == 1" @click="handleReview(scope.row)">审核</el-button>
          <el-button size="small" v-if="scope.row.status == 1 || scope.row.status == 2">预览</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分页栏 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 弹窗 -->
  <el-dialog :title="dialogTitle" v-model="addOrUpdateDialogVisable" @close="closeDialog" width="80%">
    <el-form :model="productionOrderForm" label-width="120px">
      <el-form-item label="工单编号">
        <el-input :disabled="isDetail" v-model="productionOrderForm.productionOrderCode" />

      </el-form-item>
      <el-form-item label="工单名称">
        <el-input :disabled="isDetail" v-model="productionOrderForm.productionOrderName" />
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 120px" clearable :disabled="isDetail" v-model="productionOrderForm.productionOrderSource" placeholder="单据来源">
          <el-option label="客户订单" :value="1" />
          <el-option label="库存备货" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable :disabled="isDetail" v-model="productionOrderForm.productionOrderType" placeholder="工单类型">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :key="dictData.id"
              :label="dictData.dictLabel"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工单编码">
        <el-input :disabled="isDetail" v-model="productionOrderForm.orderCode" />
      </el-form-item>
      <el-form-item label="物料编码">
        <el-input :disabled="isDetail" v-model="productionOrderForm.materialCode" />
      </el-form-item>
      <el-form-item label="工单数量">
        <el-input :disabled="isDetail" v-model="productionOrderForm.productionOrderQuantity" />
      </el-form-item>
      <el-form-item label="客户编码">
        <el-input :disabled="isDetail" v-model="productionOrderForm.customerCode" />
      </el-form-item>
      <el-form-item label="需求日期">
        <el-date-picker :disabled="isDetail" v-model="productionOrderForm.requestDate" type="date" placeholder="选择日期" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 120px;" :disabled="isDetail" v-model="productionOrderForm.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dictData in productionOrderStatusDictDataList"
              :label="dictData.dictLabel"
              :value="dictData.id"
              :key="dictData.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :disabled="isDetail" label="二维码URL">
        <el-input v-model="productionOrderForm.qrCodeUrl" />
      </el-form-item>
    </el-form>

    <el-card v-show="isDetail" >
      <template #header>
        <div class="card-header">
          <span>BOM组成</span>
        </div>
      </template>
      <template #default>
        <el-table
            :data="productionOrderBomList"
            border
            stripe
        >
          <el-table-column prop="parentMaterialId" label="主物料编号"/>
          <el-table-column prop="childMaterialId" label="组成物料编号"/>
          <el-table-column prop="unit" label="单位"/>
          <el-table-column prop="usageRatio" label="使用比例"/>
          <el-table-column prop="remark" label="备注"/>
          <el-table-column  v-if="isEdit" label="操作" width="200">
          </el-table-column>
        </el-table>
        <el-pagination
            style="margin-top: 15px"
            v-model:current-page="productionOrderBomPagination.currentPage"
            v-model:page-size="productionOrderBomPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="productionOrderBomPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleProductionOrderBomSizeChange"
            @current-change="handleProductionOrderBomCurrentPageChange"
        />
      </template>
    </el-card>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAddOrUpdate">取消</el-button>
        <el-button v-if="isEdit && productionOrderForm.status == 0" @click="confirmProductionOrderForm(productionOrderForm)">确定</el-button>
        <el-button v-if="!isEditOrAdd" type="primary" @click="saveProductionOrderForm">提交</el-button>
        <el-button v-if="isApproved && productionOrderForm.status == 1" type="primary" @click="approveProductionOrderForm(productionOrderForm)">审核通过</el-button>
        <el-button v-if="isNotApproved && productionOrderForm.status == 1" type="primary" @click="notApproveProductionOrderForm(productionOrderForm)">审核不通过</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getProductionOrderList,
  getAutoCode,
  queryById,
  addProductionOrder,
  deleteProductionOrder,
  updateProductionOrder,
  updateStatusById,
  updateStatusById2,
  updateStatusById3,
} from "@/api/production-order.js";
import {
  selectAll
} from "@/api/materialBom.js";
import { getDictDataList } from "@/api/dictData.js";

// 搜索表单数据
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  materialCode:"",
  status: "",
  productionOrderSource: "",
  customerCode:"",
  productionOrderType: ""
});
// 工单类型字典列表
const productionOrderTypeDictDataList = ref([]);
// 工单状态字典列表
const productionOrderStatusDictDataList = ref([]);
// 工单列表数据
const productionOrderList = ref([]);
// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
// Bom分页数据
const productionOrderBomPagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
// 弹窗标题
const dialogTitle = ref("");
// 弹窗显示标记
const addOrUpdateDialogVisable = ref(false);
// 编辑标记
const isEdit = ref(false);
// 新增/编辑表单数据
const productionOrderForm = ref({});
// 自动生成编号标记
const isAutoCode = ref(false);
// 显示详情标记
const isEditOrAdd = ref(false);
// 选择产品物料弹窗显示标记
const productListDialogVisable = ref(false);
//审核标记
const isApproved = ref(false);
const isNotApproved = ref(false);
//是否显示详情
const isDetail = ref(false);
const isAdd = ref(false);
//BOM组成列表
const productionOrderBomList = ref([]);
//关闭弹窗
const closeDialog = () => {
  // 清空数据
  productionOrderForm.value = {};
  isEdit.value = false;
  isDetail.value = false;
  isEditOrAdd.value = false;
  isApproved.value = false;
  isNotApproved.value = false;
  isAdd.value = false;
}
//查看工单
const handlerShowProcess = (row) => {
  dialogTitle.value = '查看工单'
  isEdit.value = false;
  isDetail.value = true;
  isEditOrAdd.value = true;
  isApproved.value =false;
  isNotApproved.value =false;
  queryById(row.id).then((res) => {
    productionOrderForm.value = res.data;
    addOrUpdateDialogVisable.value = true;
    LoadProductionOrderBomList(row.id);
  });
}
// 审核工单
const handleReview = (row) => {
  dialogTitle.value = "审核工单";
  isEditOrAdd.value = true;
  isApproved.value = true;
  isNotApproved.value = true;
  queryById(row.id).then((res) => {
    productionOrderForm.value = res.data;
    addOrUpdateDialogVisable.value = true;
  });
};
// 编辑工单
const handleEdit = (row) => {
  dialogTitle.value = "编辑工单";
  isEdit.value = true;
  isEditOrAdd.value = false;
  isDetail.value = false;
  queryById(row.id).then((res) => {
    productionOrderForm.value = res.data;
    addOrUpdateDialogVisable.value = true;
  });
};

const confirmProductionOrderForm = (row) => {
  ElMessageBox.confirm(
      `确定此工单"${row.productionOrderName}"吗？`,
      "确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    updateStatusById(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success("状态更改成功");
        cancelAddOrUpdate();
        handleSearch();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}
//审核通过表单
const approveProductionOrderForm = (row) => {
  ElMessageBox.confirm(
      `确定审核通过此工单"${row.productionOrderName}"吗？`,
      "确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    updateStatusById3(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success("状态更改成功");
        cancelAddOrUpdate();
        handleSearch();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};
//审核不通过表单
const notApproveProductionOrderForm = (row) => {
  ElMessageBox.confirm(
      `确定审核不通过此工单"${row.productionOrderName}"吗？`,
      "确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    updateStatusById2(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success("状态更改成功");
        cancelAddOrUpdate();
        handleSearch();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};
// 提交新增/编辑表单
const saveProductionOrderForm = () => {
  if (isEdit.value) {
    updateProductionOrder(productionOrderForm.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success("编辑成功");
        cancelAddOrUpdate();
        handleSearch();
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    addProductionOrder(productionOrderForm.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success("新增成功");
        cancelAddOrUpdate();
        handleSearch();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};
// 取消新增/编辑
const cancelAddOrUpdate = () => {
  addOrUpdateDialogVisable.value = false;
  closeDialog();
};
// 自动生成编号
const autoCode = () => {
  // 这里可补充自动生成编号的逻辑，比如调用接口获取自动生成的编号
  getAutoCode().then((res) => {
    if (res.code === 200) {
      productionOrderForm.value.productionOrderCode = res.data;
    }
  });
};
// 新增工单
const handleAdd = () => {
  dialogTitle.value = "新增工单";
  closeDialog();
  addOrUpdateDialogVisable.value = true;
};
// 搜索工单列表
const handleSearch = () => {
  getProductionOrderList(
      pagination.value.currentPage,
      pagination.value.pageSize,
      searchForm.value
  ).then((res) => {
    productionOrderList.value = res.data.list;
    pagination.value.total = res.data.total;
  });
};
//加载工单BOM组成
const LoadProductionOrderBomList = (productionOrderId) => {
  selectAll({productionOrderId:productionOrderId,pageNum:productionOrderBomPagination.currentPage,pageSize:productionOrderBomPagination.pageSize})
      .then(res=>{
        productionOrderBomList.value = res.data.list;
        productionOrderBomPagination.total = res.data.total;
      })
}

// 处理每页大小改变
const handleProductionOrderBomSizeChange = (newSize) => {
  productionOrderBomPagination.value.pageSize = newSize;
  LoadProductionOrderBomList(productionOrderForm.id);
};
// 处理当前页改变
const handleProductionOrderBomCurrentPageChange = (newPage) => {
  productionOrderBomPagination.value.pageSize = newPage;
  LoadProductionOrderBomList(productionOrderForm.id);
};
// 处理每页大小改变
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize;
  handleSearch();
};
// 处理当前页改变
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  handleSearch();
};
// 重置搜索
const resetSearch = () => {
  searchForm.value.productionOrderCode = "";
  searchForm.value.productionOrderName = "";
  searchForm.value.status = "";
  searchForm.value.materialCode = "";
  searchForm.value.customerCode = "";
  searchForm.value.productionOrderSource = "";
  searchForm.value.productionOrderType = "";
  handleSearch();
};
// 加载工单状态字典
const loadProductionOrderStatusDictDataList = () => {
  getDictDataList({ dictType: "PRODUCTION_ORDER_STATUS" }).then((res) => {
    productionOrderStatusDictDataList.value = res.data.records;
  });
};
// 加载工单类型字典
const loadProductOrderDictDataList = () => {
  getDictDataList({ dictType: "PRODUCTION_ORDER_TYPE" }).then((res) => {
    productionOrderTypeDictDataList.value = res.data.records;
  });
};



// 删除工单
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除工单"${row.productionOrderName}"吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    deleteProductionOrder(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        handleSearch();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

onMounted(() => {
  loadProductionOrderStatusDictDataList();
  loadProductOrderDictDataList();
  handleSearch();
});
</script>
<style scoped>
.customer-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>